package gov.pbc.nn.core.bdf.view;

import gov.pbc.nn.core.bdf.entity.Dept;
import gov.pbc.nn.core.bdf.entity.User;
import gov.pbc.nn.core.dao.PbcnnCoreHibernateDao;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.bstek.bdf2.core.CoreHibernateDao;
import com.bstek.bdf2.core.model.UserDept;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;
import com.bstek.dorado.annotation.Expose;
import com.bstek.dorado.core.Configure;

@Component("userInit")
public class UserInit{
	
	@Resource(name = PbcnnCoreHibernateDao.BEAN_ID)
	private PbcnnCoreHibernateDao coreHibernateDao;
	
	@Autowired
	@Qualifier("bdf2.passwordEncoder")
	private PasswordEncoder passwordEncoder;
	
	@Expose
	@Transactional
	public <T> void init() throws Exception {
		if (StringUtils.equals("debug", Configure.getString("core.runMode"))) {
			// 创建saxReader对象
			SAXReader reader = new SAXReader();
			Document document = null;
			try (InputStream in = this.getClass().getResourceAsStream("user.xml");) {
				document = reader.read(in);
			}
			// 获取根节点元素对象
			Element node = document.getRootElement();

			final List<Element> list1 = new ArrayList<Element>();
			list1.addAll(node.elements());

			this.coreHibernateDao.doInHibernateSession(new ISessionCallback<Void>() {

				@Override
				public Void doInSession(Session session) {
					//int maxUsername = Integer.parseInt(generalUsername(session));
					for (int i = 0; i < list1.size(); i++) {
						// 保存用户表
						User u = new User();
						u.setUsername(list1.get(i).element("uid").getText());
						u.setFkSysName((list1.get(i).element("uid").getText()));
						u.setCname(list1.get(i).element("username").getText());
						u.setIdentity(list1.get(i).element("pbcIdCard").getText());
						String female = list1.get(i).element("pbcgender").getText();
						u.setMale(female.equals("1")?false:true);
						// 数据库设置不能为空
						u.setCompanyId("PBCNN");
						int salt = RandomUtils.nextInt(1000);
						u.setSalt(String.valueOf(salt));
						String password = Configure.getString("default.password");
						u.setPassword(passwordEncoder.encodePassword(password, salt));
						 session.save(u);

						// 保存用户关系
						UserDept ud = new UserDept();
						ud.setId(UUID.randomUUID().toString());
						ud.setUsername(u.getUsername());
						String deptIdDirt = list1.get(i).element("departmentnumber").getText();
						// <departmentnumber>ou=13380,cn=org,dc=nng,dc=pbc</departmentnumber>
						// 通过字符串截取以,为分割先的第一个字符串，然后再解掉前三位
						//String string = deptIdDirt.split(",")[0];
						//String deptString = string.substring(3);
						ud.setDeptId(deptIdDirt);
						 session.save(ud);
					}
					return null;
				}
			});
		}
	}

	private String generalUsername(Session session) {
		String sql = "select max(u.USERNAME_) from t_user u where u.USERNAME_ REGEXP '^U[0-9]+$'";
		String maxUsername = (String) session.createSQLQuery(sql).uniqueResult();
		if (StringUtils.isEmpty(maxUsername)) {
			maxUsername = "99999";
		} else {
			maxUsername = String.valueOf(Long.parseLong(maxUsername.substring(1)));
		}
		return maxUsername;
	}
	

}
